package com.way.cloud.common.knife4j;

import com.way.cloud.common.knife4j.properties.Knife4jGlobalProperties;
import com.way.cloud.common.knife4j.properties.Knife4jProperties;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@EnableConfigurationProperties({Knife4jGlobalProperties.class, Knife4jProperties.class})
public class Knife4jConfiguration {

    @Resource
    private Knife4jGlobalProperties globalProps;
    @Resource
    private Knife4jProperties props;

    @Bean
    @ConditionalOnMissingBean
    public OpenAPI customOpenAPI() {
        return new OpenAPI().info(customInfo());
    }

    private Info customInfo() {
        String title = props.getTitle() != null ? props.getTitle() : globalProps.getTitle();
        String version = props.getVersion() != null ? props.getVersion() : globalProps.getVersion();
        String author = props.getAuthor() != null ? props.getAuthor() : globalProps.getAuthor();
        log.info("Load Knife4j Success!... title:{}, version:{}, author:{}", title, version, author);
        return new Info()
                .title(title)
                .version(version)
                .description(globalProps.getDescription())
                .license(new License()
                        .name(globalProps.getLicense())
                        .url(globalProps.getLicenseUrl()))
                .contact(new Contact()
                        .name(author)
                        .email(globalProps.getEmail())
                );
    }

}
